<?php
namespace Wj\Encipher\Asymmetric;
class Hash {

    private $aliase = "sha256";
    private $binary = false;
    private $options = [];
    public function __construct(string $aliase = null, bool $binary = false, array $options = []) {
        if (!empty($aliase)) {
            if ($this->checkaliase($aliase)) {
                $this->aliase = $aliase;
            }
        }
        if ($binary) {
            $this->binary = true;
        }
    }

    public function checkaliase(string $aliase) {
        $list = hash_algos();
        if (!in_array($aliase, $list)) {
            throw new \Throwable("aliase:" . $aliase . " is not supported by openssl");
        }
        return true;
    }

    public function encrypt(string $plaintext): string {
        return hash($this->aliase, $plaintext, $this->binary, $this->options);
    }
    /**
     * 生成密钥
     *
     * @param  integer $type
     * @return void
     * @author wj
     * @date 2024-11-09
     */
    public function generatesecret(int $type = 0) {
        $uid = md5(uniqid(rand(), true) . microtime());
        $hash = $this->encrypt($uid);
        $arr = str_split($hash);
        foreach ($arr as $v) {
            if ($type == 0) {
                $newArr[] = empty(rand(0, 1)) ? strtoupper($v) : $v;
            }
            if ($type == 1) {
                $newArr[] = strtoupper($v);
            }
            if ($type == 2) {
                $newArr[] = $v;
            }
        }
        return implode('', $newArr);
    }
}
